package com.appbee.gdata.youtube.client.cell;

import javax.inject.Inject;

import com.appbee.gdata.youtube.client.model.SimpleEntry;
import com.appbee.gdata.youtube.client.ui.IYoutubeStyle;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.cell.client.ValueUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.safehtml.client.SafeHtmlTemplates;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;

public class SimpleEntryRemoveCell extends AbstractCell<SimpleEntry>
{
	interface Template extends SafeHtmlTemplates
	{
		@Template("<div class=\"{0}\">{1}</div>")
		SafeHtml div(String styleName,SafeHtml content);
		
		@Template("<img class=\"{0}\" src=\"{1}\"></img>")
		SafeHtml img(String styleName,String src);
		
		@Template("<button class=\"{0}\" value=\"{1}\"></button>")
		SafeHtml button(String styleName,String value);
	}
	
	
	private static final Template template = GWT.create(Template.class);
	private final IYoutubeStyle style;
	
	private RemoveSimpleEntryListener listener;
	
	@Inject
	public SimpleEntryRemoveCell(IYoutubeStyle style)
	{
		super("click");
		this.style = style;
	}

	public void setListener(RemoveSimpleEntryListener listener)
	{
		this.listener = listener;
	}

	@Override
	public void render(com.google.gwt.cell.client.Cell.Context context,
			SimpleEntry value, SafeHtmlBuilder sb)
	{
		render(context, value, sb,false);
	}

	public void render(com.google.gwt.cell.client.Cell.Context context,
			SimpleEntry value, SafeHtmlBuilder sb,boolean mynd)
	{
		SafeHtmlBuilder cSb = new SafeHtmlBuilder();
		String thumbnail = value.getThumbnail();
		if(thumbnail!=null && thumbnail.length()>0)
		{
			cSb.append(template.img(style.media(), thumbnail));
		}		
		int d = value.getDuration();
		int m = d/60;
		int s = d%60;
		String duration = m+":"+NumberFormat.getFormat("00").format(s);
		cSb.append(template.div(style.entryDuration(),SafeHtmlUtils.fromString(duration)));
		
		cSb.append(template.div(style.entryContent(), SafeHtmlUtils.fromString(value.getTitle())));
		cSb.append(template.button(style.deleteButton(), "remove"));

		sb.append(template.div(style.entryWrap(),cSb.toSafeHtml()));
		
	}

	@Override
	public void onBrowserEvent(com.google.gwt.cell.client.Cell.Context context,
			Element parent, SimpleEntry value, NativeEvent event,
			ValueUpdater<SimpleEntry> valueUpdater)
	{
		String type = event.getType();
		Element target = event.getEventTarget().cast();
		if ("click".equals(type) && "BUTTON".equals(target.getTagName()))
		{
			if(listener!=null) listener.onRemove(value);
		}
		super.onBrowserEvent(context, parent, value, event, valueUpdater);
	}

	
	

}
